# Copyright (c) 2008 Todd A. Fisher
# see LICENSE
require 'esi/esi'
require 'esi/tag/base'
require 'esi/tag/include'
require 'esi/tag/invalidate'
require 'esi/tag/attempt'
require 'esi/tag/except'
require 'esi/tag/try'

module ESI
  class Parser < CParser
    def initialize( router, cache, max_depth )
      @router = router
      @cache = cache
      @max_depth = max_depth
      
      end_tag_handler do|tag_name|
        if self.esi_tag.name == tag_name.gsub(/esi:/,'')
          self.esi_tag.close(self.output)
          self.esi_tag = nil
        else
          self.esi_tag.close_child(self.output,tag_name)
        end
      end
    end

    def prepare( request_params, http_params, &block )
      start_tag_handler do|tag_name, attrs|
        tag = ESI::Tag::Base.create( @router,
                                     request_params,
                                     http_params,
                                     tag_name.gsub(/esi:/,''),
                                     attrs,
                                     @cache )
        # set the tag depth
        tag.depth = self.depth if tag.respond_to?(:depth=)
        tag.max_depth = @max_depth if tag.respond_to?(:max_depth=)

        if self.esi_tag
          self.esi_tag.add_child(tag)
        else
          self.esi_tag = tag
        end
      end
      self.output=block if block_given?
    end

  end
end
